<script setup lang="ts">
  import { ref, useTemplateRef, reactive } from 'vue'
  import { useQuasar } from 'quasar'
  import CudTable, { type TQTableColumns, type TRequestParam } from '@/components/CudTable.vue'
  import {
    addMessage,
    getMessagePageList,
    // removeMessage,
    editMessage,
    getBannerList,
    editBanner,
    // removeBanner,
    addBanner
  } from '@/api'
  import { isRequestSuccess, onSubmit } from '@/utils'

  const $q = useQuasar()
  const tab = ref('banner-adv')
  const rDialogForm = useTemplateRef('dialogForm')
  const rShowDialog = ref(false)
  const rDialogTitle = ref('')

  const rId = ref(null)
  const rType = ref(0)
  const rBannerOrder = ref('0')
  const rLink = ref('')
  const rImageUrl = ref('')

  // banner
  const bannerColumns: TQTableColumns = [
    {
      name: 'bannerOrder',
      label: 'banner序号',
      style: '100px',
      field: 'bannerOrder',
      align: 'left',
      headerClasses: 'ud-wp-10',
      classes: 'ud-wp-10'
    },
    {
      name: 'link',
      label: '链接',
      field: 'link',
      align: 'left',
      headerClasses: 'ud-wp-40',
      classes: 'ud-wp-40'
    },
    {
      name: 'imageUrl',
      label: '图片',
      field: 'imageUrl',
      align: 'left',
      headerClasses: 'ud-wp-40',
      classes: 'ud-wp-40'
    },
    {
      name: 'operate',
      label: '操作',
      style: '100px',
      field: 'operate',
      align: 'center',
      headerClasses: 'ud-wp-10',
      classes: 'ud-wp-10'
    }
  ]
  const bannerTableRef = useTemplateRef('bannerTable')
  function bannerRequest() {
    // const { page, rowsPerPage } = context.pagination
    return getBannerList(0)
  }
  // adv
  const advColumns: TQTableColumns = [
    {
      name: 'bannerOrder',
      label: '广告序号',
      style: '100px',
      field: 'bannerOrder',
      align: 'left',
      headerClasses: 'ud-wp-10',
      classes: 'ud-wp-10'
    },
    {
      name: 'link',
      label: '链接',
      field: 'link',
      align: 'left',
      headerClasses: 'ud-wp-40',
      classes: 'ud-wp-40'
    },
    {
      name: 'imageUrl',
      label: '图片',
      field: 'imageUrl',
      align: 'left',
      headerClasses: 'ud-wp-40',
      classes: 'ud-wp-40'
    },
    {
      name: 'operate',
      label: '操作',
      style: '100px',
      field: 'operate',
      align: 'center',
      headerClasses: 'ud-wp-10',
      classes: 'ud-wp-10'
    }
  ]
  const advTableRef = useTemplateRef('advTable')
  function advRequest() {
    // const { page, rowsPerPage } = context.pagination
    return getBannerList(1)
  }

  function onShowDialog(row: any) {
    // 类型（0: Banner, 1: 广告）
    const { type, bannerOrder, link, imageUrl } = row
    rDialogTitle.value = type === 1 ? '广告' : 'Banner'
    rType.value = type || 0
    rId.value = row.id
    rBannerOrder.value = bannerOrder || ''
    rLink.value = link || ''
    rImageUrl.value = imageUrl || ''
    rShowDialog.value = true
  }
  function onCancel() {
    rShowDialog.value = false
  }
  function refreshUserGrid(type: number) {
    const tableRef = type ? advTableRef : bannerTableRef
    if (tableRef.value) {
      tableRef.value.refreshUserTable(1)
    }
  }
  function onDialogSubmit() {
    onSubmit(rDialogForm, async () => {
      const data: any = {
        type: rType.value,
        bannerOrder: rBannerOrder.value,
        link: rLink.value,
        imageUrl: rImageUrl.value
      }
      if (rId.value) {
        data.id = rId.value
      }
      const res = await (rId.value ? editBanner(data) : addBanner(data))
      if (isRequestSuccess(res)) {
        $q.notify({
          type: 'positive',
          message: '提交成功'
        })
        refreshUserGrid(data.type)
      } else {
        $q.notify({
          color: 'red-5',
          textColor: 'white',
          icon: 'warning',
          message: '提交失败'
        })
      }
      onCancel()
    })
  }
  // function onRemoveBanner(row: any) {
  //   $q.dialog({
  //     title: '确认',
  //     message: '你确定要删除这个条记录吗?',
  //     cancel: true,
  //     persistent: true
  //   }).onOk(() => {
  //     removeBanner(row.id)
  //       .then(res => {
  //         if (isRequestSuccess(res)) {
  //           refreshUserGrid(row.type)
  //         }
  //       })
  //       .catch(error => {
  //         console.log(error)
  //       })
  //   })
  // }
  // message
  const columns: TQTableColumns = [
    { name: 'title', label: '消息标题', field: 'title', align: 'left' },
    { name: 'content', label: '消息内容', field: 'content', align: 'left' },
    {
      name: 'type',
      label: '消息类型',
      field: 'type',
      format: val => {
        return val == 1 ? '通知' : val == 2 ? '公告' : val == 3 ? '私信' : val
      },
      align: 'left'
    },
    { name: 'createdAt', label: '创建时间', field: 'createdAt', align: 'left' },
    { name: 'operate', label: '操作', field: 'operate', align: 'center' }
  ]
  const formRef = useTemplateRef('form')
  const rMsg = reactive({ title: '', type: 1, content: '' })
  const msgTableRef = useTemplateRef('msgTable')
  const rowIdRef = ref(-1)

  function request(context: TRequestParam) {
    const { page, rowsPerPage } = context.pagination
    return getMessagePageList(undefined, page, rowsPerPage)
  }
  async function submitData() {
    const res = await (rowIdRef.value === -1
      ? addMessage({ ...rMsg })
      : editMessage({ ...rMsg, id: rowIdRef.value }))
    if (isRequestSuccess(res)) {
      $q.notify({
        type: 'positive',
        message: '提交成功'
      })
      if (msgTableRef.value) {
        msgTableRef.value.refreshUserTable(1)
      }
      onReset()
    } else {
      $q.notify({
        color: 'red-5',
        textColor: 'white',
        icon: 'warning',
        message: '提交失败'
      })
    }
  }
  function onMessageSubmit() {
    onSubmit(formRef, submitData)
  }
  function onReset() {
    rowIdRef.value = -1
    Object.assign(rMsg, { title: '', type: 1, content: '' })
  }
  function onRetEditContent(data: any) {
    const { id, title, type, content } = data.row
    rowIdRef.value = id
    Object.assign(rMsg, { title, type, content })
  }
  // async function onRemove(data: any) {
  //   const res = await removeMessage(data.row.id)
  //   if (isRequestSuccess(res)) {
  //     if (msgTableRef.value) {
  //       msgTableRef.value.refreshUserTable(1)
  //     }
  //   }
  // }
</script>

<template>
  <q-page class="bg-[#FAFCFF] p-5">
    <q-tabs
      v-model="tab"
      dense
      active-color="primary"
      indicator-color="primary"
      align="left"
      narrow-indicator>
      <q-tab name="banner-adv" label="banner/广告" />
      <q-tab name="custom-message" label="自定义消息" />
    </q-tabs>

    <q-separator />

    <q-tab-panels v-model="tab" animated class="bg-transparent">
      <q-tab-panel name="banner-adv">
        <CudTable
          ref="bannerTable"
          class="bg-white"
          title="banner"
          :columns="bannerColumns"
          hide-pagination
          :request="bannerRequest">
          <template v-slot:body-cell-operate="props">
            <td class="text-center">
              <span @click="onShowDialog(props.row)" class="text-[#2265D4] cursor-pointer">
                编辑
              </span>
              <!--              <span @click="onRemoveBanner(props.row)" class="text-[#EB4242] cursor-pointer ml-2">
                删除
              </span>-->
            </td>
          </template>
          <!--          <template v-slot:top-right>
            <q-btn color="primary" unelevated label="新增" @click="onShowDialog({})" />
          </template>-->
        </CudTable>
        <CudTable
          ref="advTable"
          class="bg-white mt-5"
          title="广告"
          hide-pagination
          :columns="advColumns"
          :request="advRequest">
          <template v-slot:body-cell-operate="props">
            <td class="text-center">
              <span @click="onShowDialog(props.row)" class="text-[#2265D4] cursor-pointer">
                编辑
              </span>
            </td>
          </template>
        </CudTable>
        <q-dialog v-model="rShowDialog" class="ud-dialog">
          <q-card class="!max-w-none w-[60%]">
            <q-card-section>
              <div class="text-h6 text-[#409EFD] relative">
                <b class="v-blue-line"></b>
                {{ rDialogTitle }}
              </div>
            </q-card-section>

            <q-card-section class="q-pt-none">
              <q-form @submit="onDialogSubmit" ref="dialogForm">
                <q-input
                  class="w-[90%]"
                  outlined
                  dense
                  placeholder="请输入序号"
                  v-model="rBannerOrder"
                  hint=""
                  lazy-rules
                  :rules="[val => !!val || '请输入序号']">
                  <template v-slot:before>
                    <span class="inline-block w-20 text-right text-lg text-[#333]">序号:</span>
                  </template>
                </q-input>
                <q-input
                  class="w-[90%]"
                  outlined
                  dense
                  placeholder="请输入链接地址"
                  v-model="rLink"
                  hint=""
                  lazy-rules
                  :rules="[val => (val && val.length > 0) || '请输入链接地址']">
                  <template v-slot:before>
                    <span class="inline-block w-20 text-right text-lg text-[#333]">链接地址:</span>
                  </template>
                </q-input>
                <q-input
                  class="w-[90%]"
                  outlined
                  dense
                  placeholder="请输入图片地址"
                  v-model="rImageUrl"
                  hint=""
                  lazy-rules
                  :rules="[val => (val && val.length > 0) || '请输入图片地址']">
                  <template v-slot:before>
                    <span class="inline-block w-20 text-right text-lg text-[#333]">图片地址:</span>
                  </template>
                </q-input>

                <div class="flex flex-center gap-7">
                  <q-btn
                    color="blue-6"
                    padding="10px 30px"
                    text-color="white"
                    label="确认"
                    type="submit" />
                  <q-btn
                    outline
                    padding="10px 30px"
                    @click="onCancel"
                    color="light-blue"
                    label="取消" />
                </div>
              </q-form>
            </q-card-section>
          </q-card>
        </q-dialog>
      </q-tab-panel>

      <q-tab-panel name="custom-message" class="px-0">
        <div class="p-5 bg-white mb-5">
          <div class="text-xl font-semibold text-[#333] mb-5">自定义消息</div>
          <q-form @submit="onMessageSubmit" @reset="onReset" ref="form">
            <q-input
              class="w-[40%]"
              outlined
              dense
              placeholder="请输入信息标题，建议12字以内"
              v-model="rMsg.title"
              hint=""
              lazy-rules
              :rules="[val => (val && val.length > 0) || '请输入信息标题']">
              <template v-slot:before>
                <span class="text-lg text-[#333]">信息标题:</span>
              </template>
            </q-input>
            <div class="flex items-center mb-5">
              <span>消息类型:</span>
              <div class="flex-1">
                <q-radio v-model="rMsg.type" :val="1" label="通知" />
                <q-radio v-model="rMsg.type" :val="2" label="公告" />
                <q-radio v-model="rMsg.type" :val="3" label="私信" />
              </div>
            </div>
            <q-input
              class="mb-3"
              outlined
              dense
              placeholder="请输入信息内容"
              v-model="rMsg.content"
              hint=""
              type="textarea"
              lazy-rules
              :rules="[val => (val && val.length > 0) || '请输入信息内容']">
              <template v-slot:before>
                <span class="text-lg text-[#333]">信息内容:</span>
              </template>
            </q-input>

            <div class="flex flex-center gap-7">
              <q-btn
                color="blue-6"
                padding="10px 30px"
                text-color="white"
                label="确认提交"
                type="submit" />
              <q-btn outline padding="10px 30px" type="reset" color="light-blue" label="清空" />
            </div>
          </q-form>
        </div>

        <CudTable ref="msgTable" title="发送历史" :columns="columns" :request="request">
          <template v-slot:body-cell-operate="props">
            <td class="text-center">
              <span @click="onRetEditContent(props)" class="text-[#2265D4] cursor-pointer">
                编辑
              </span>
              <!--              <span @click="onRemove(props)" class="text-[#EB4242] cursor-pointer ml-2">删除</span>-->
            </td>
          </template>
        </CudTable>
      </q-tab-panel>
    </q-tab-panels>
  </q-page>
</template>
